package com.webapp.schedule;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import javax.security.auth.login.LoginException;

import org.apache.log4j.Logger;

import com.inforim.cognos.CognosClient;
import com.inforim.cognos.plugins.CognosReportPlugin;
import com.inforim.cognos.utils.CognosHelper;
import com.webapp.cognos.CogOpt;
import com.webapp.loader.XmlReportsLoader;
import com.webapp.module.CogUser;
import com.webapp.module.MailSubscriber;
import com.webapp.module.Report;
import com.webapp.util.PathRule;

public class TestClient {
	static Logger logger = Logger.getLogger(TestClient.class);
	private static Object debug;
	private static LinkedList reportLose;
	
	public static void main(String[] args) {
		XmlReportsLoader xmlReportsLoader = new XmlReportsLoader();
		xmlReportsLoader.load();
		CognosClient cognosClient = CognosHelper.getClient();
		cognosClient.setDispatch(xmlReportsLoader.getC8_URL());
		cognosClient.setUsername(xmlReportsLoader.getC8_USERNAME());
		cognosClient.setPassword(xmlReportsLoader.getC8_PASSWORD());
		cognosClient.setNamespace(xmlReportsLoader.getC8_NAMESPACE());
		try {
			cognosClient.logon();
		} catch (LoginException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			System.err.println("----------cognos 连接失败------------");
		}
		
		System.err.println("------完成------");
		Map reports = xmlReportsLoader.getReportList();
		Report report = null;
		String format = null;
		Calendar cal = Calendar.getInstance();
		cal.add(Calendar.DATE, -1); // DATE=5 前一天
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
//		String paramString = "date=" + sdf.format(cal.getTime()) + "T00:00:00.000";
//		String paramString = "Year=FY17|Month=1|Currency=Consolidation_in_HKD|Office=Beijing|SubBU=ADV-Consulting";
		String paramString = null;
		MailSubscriber subscriber = null;
		List attachfiles = new ArrayList();
		String attachfile = null;
		//连接、报表、null,时间，参数设置
		runReport(cognosClient, (Report)reports.get("000"), format, cal, paramString,
				subscriber, attachfiles, attachfile);
		
		System.out.println("---------------------xxxxxxxx--------------");
	}


	/**
	 * 
	 * @param cognosClient 连接
	 * @param report    报表
	 * @param format    文件类型
	 * @param cal       时间
	 * @param paramString   参数设置
	 * @param subscriber
	 * @param attachfiles
	 * @param attachfile
	 */
	private static void runReport(CognosClient cognosClient, Report report,
			String format, Calendar cal, String paramString,
			MailSubscriber subscriber, List attachfiles, String attachfile) {
		// TODO Auto-generated method stub

		boolean isOK = false;
		try {
			CognosReportPlugin cognosReportPlugin = CognosHelper
					.getReportPlugin();
			cognosReportPlugin.setClient(cognosClient);

			String path = PathRule.getHKSavePath(report.getSavefolder());

			String tempformat = null;
			if (format != null)
				tempformat = format;
			else {
				tempformat = report.getFileFormat();
			}
			String fileName = "";
			fileName = PathRule.getHKReportName(report.getPrefixFilename(),
					cal.getTime(), tempformat);
			logger.info("Running the report...ReportId:"+report.getId());
			logger.info("Report search path is:" + report.getSearchpath());

			long beginTime = System.currentTimeMillis();
			
//			ContentManagerServiceStub cmStub = null;
//			ReportServiceStub repStub = null;
//			String path
//			String params,
//			String saveAs
//			Properties props = null;
			isOK = cognosReportPlugin.runReport(null, null,
					report.getSearchpath(), paramString, path + fileName, null);
			long endTime=System.currentTimeMillis();
			logger.info("Running report has used "+(endTime-beginTime)/1000+"sec!");
			if (!(isOK)) {
//				reportLose.offer(report);
				logger.info("Report running failure! Add to failure queue and retry later! reportId:"+ report.getId()+" searchpath:"+report.getSearchpath());
			} else {
				logger.info("Report running success! Report has exported on server "+path+fileName);
//				subscriber = report.getMail();
//				getMailSubscriber(cognosReportPlugin, report.getSearchpath(),
//						subscriber.getTo());
				logger.info("Email sending....");
				// Jcopy.CopyFile(runreport.getSaveLocation() + File.separator +
				// runreport.getFileName(), report.getCopyfolder());
//				Jcopy.CopyFile(path + fileName, report.getCopyfolder()); // 复制到网盘上
//				\\Honsxfile001\Public\Rx Sales Team\Rx - Admin\frCognos\Daily Sales Report By BU_Budget.xls (找不到网络路径。)
				// 邮件内容
//				SendMail mail = new SendMail();
//				mail.setSMTPHost(XmlReportsLoader.getMAIL_HOST());
//				mail.setUser(XmlReportsLoader.getMAIL_USER());
//				mail.setPassword(XmlReportsLoader.getMAIL_PWD());
//				subscriber = report.getMail();
//				mail.setFrom(subscriber.getFrom());
//				if (debug != null && debug.equals("true")) {
//					mail.setTo("cz902811@gsk.com");
////				} else if(null!=subscriber.getTo()&&!subscriber.getTo().equals("")){
////					mail.setTo(subscriber.getTo());
//				}else{
//					mail.setTo(getMailSubscriber(cognosReportPlugin,
//							report.getSearchpath(), subscriber.getTo()));
//				}
//
//				mail.setSubject(subscriber.getSubject());
//				mail.setContent(subscriber.getContent());
//
//				boolean isAttach = false;
//				if (attachfile != null)
//					isAttach = Boolean.parseBoolean(attachfile);
//				else {
//					isAttach = subscriber.isAttachfile();
//				}
//				if (isAttach) {
//					attachfiles.clear();
//					// attachfiles.add(runreport.getSaveLocation() +
//					// File.separator + runreport.getFileName());
//					attachfiles.add(path + fileName);
//					mail.setFileList(attachfiles);
//				}
//
//				isOK = mail.send();
//				if (!(isOK)) {
//					reportLose.offer(report);
//					System.out.println("Report Sending failure! Add to failure queue! reportId:"
//							+ report.getId());
//				} else {
//					System.out.println("Report Sending success! reportId:"
//							+ report.getId());
//				}

			}

			// cmService.logoff();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	
	private static String getMailSubscriber(
			CognosReportPlugin cognosReportPlugin, String searchpath,
			String defaultMailTo) {
		StringBuffer emailto = new StringBuffer(defaultMailTo);
		CogOpt cp = new CogOpt();
		cp.getRolePerFromCogObj(cognosReportPlugin.getClient(), searchpath);
		// cognosReportPlugin.getRolePerFromCogObj(searchpath);
		List userlist = cp.getUserlist();
		Iterator iter = userlist.iterator();
		CogUser cu = null;
		while (iter.hasNext()) {
			if (emailto.length() > 0) {
				emailto.append(',');
			}
			cu = (CogUser) iter.next();
			String email=cu.getCoguser_email().trim();
			//去除空格
			email=email.replaceAll(" ", "");
			emailto.append(email);
		}
		return emailto.toString();
	}
	
	
}
